package main

import (
	"encoding/json"
	"fmt"
	"github.com/goinggo/mapstructure"
	"golang.org/x/net/websocket"

	"game-server/src/protocol/areacode"
	"game-server/src/protocol/opcode"

	"github.com/sirupsen/logrus"
)

//网络数据结构
//1	websocket的网络链接
//2	strmd5	房间的加密信息
type NetData struct{
	Connection *websocket.Conn
	StrMd5	string
}
type RequestBody struct{
	req string
}
//json->map:数据的处理
func (r *RequestBody)Json2Map()(s map[string]interface{},err error){
	var result map[string]interface{}
	if err := json.Unmarshal([]byte(r.req), &result); err != nil {
		logrus.Info("json2map:",err.Error())
		return nil,err
	}
	return result,nil
}

//网络层处理数据
//1.针对服务器而言 一直等待消息
//for...

func (this *NetData) Receive(){
	for{
		var content string
		if err := websocket.Message.Receive(this.Connection, &content); err != nil {
			break
		}
		if len(content) == 0 {
			break
		}

		fmt.Println(content)
		//正常处理
		this.SyncMessageHandler(content)
	}
}
func (this *NetData)SyncMessageHandler(content string){
	//	1 字符串-->其他格式 必须高效(大量并发情况下依然不影响性能 )
	//2实现格式 主协议 子协议  struct
	//3处理函数
	var r RequestBody
	r.req=content
	if protocolData, err := r.Json2Map(); err == nil {

		head:=(protocolData["HeadProto"]).(map[string]interface{})
		var areaCode int =(int)((head["AreaCode"]).(float64))
		var opCode int =(int)((head["OpCode"]).(float64))

		this.HandleAreaProtocol(areaCode,opCode,protocolData)
	}else {
		fmt.Println("解析失败:",err.Error())
	}
}
//处理函数,底层函数,必须面向所有的数据处理
func (this *NetData) HandleAreaProtocol(areaCode int,opCode int,protocolData map[string]interface{},){
	//return
	switch areaCode {
		case areacode.DB:
		{

		}
		case areacode.GAME:
		{
			this.HandleOpcodeProtocol(opCode,protocolData)
		}
	default:
		panic("主协议:不存在!!!")
	}

}
//处理子协议
func (this *NetData) HandleOpcodeProtocol(opCode int,protocolData map[string]interface{}){
	switch opCode {
		case opcode.C2S_PLAYER_LOGIN_CODE:{
			this.PlayerLogin(protocolData)
		}
		default:
		{

		}

	}
}
func (this *NetData)PlayerLogin(protocolData map[string]interface{}) {
	fmt.Println("玩家登陆")

	//protocolData.(opcode.C2S_PLAYER_LOGIN)
	var playerLoginData opcode.C2S_PLAYER_LOGIN
	err:=mapstructure.Decode(protocolData,&playerLoginData)
	if err==nil {
		fmt.Println(playerLoginData)
		//playerLoginData
	}
}
